package com.example.springqrcraft.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 孤霜
 * @version 1.0
 */
@Controller
@ResponseBody
public class QrCraft {
    @GetMapping("/qr")
    public void qr(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
                   ) {
        try {
            String url = httpServletRequest.getParameter("url");
            Map map = new HashMap<>();
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");
            map.put(EncodeHintType.MARGIN, 1);
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, 300, 300, map);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for(int x=0;x<width;x++) {
                for(int y=0;y<height;y++) {
                    image.setRGB(x,y,bitMatrix.get(x,y)?0xFF000000:0xFFFFFFFF);
                }
            }
            ServletOutputStream out= httpServletResponse.getOutputStream();
            ImageIO.write(image,"png",out);
            out.flush();
            out.close();
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
